package com.zb.frame.modules.common.upgrade;

import com.zb.frame.base.upgrade.UpgradeColumn;
import com.zb.frame.base.upgrade.UpgradeTable;
import com.zb.frame.base.upgrade.common.UpgradeHelper;
import com.zb.frame.base.upgrade.common.UpgradeTask;
import com.zb.frame.base.upgrade.enums.DBType;
import com.zb.frame.base.upgrade.enums.ValueType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;


public class UpgradeTask_New extends UpgradeTask {
	
	private static final Logger logger = LoggerFactory.getLogger(UpgradeTask_New.class);

	@Override
	public String getNewVersion() {
		return "0.0.1";
	}

	@Override
	public boolean doUpgrade(Connection conn, DBType type) {
		try {
			createTableUserToken(conn, type, "sys_user_token", "用户Token表");
			return true;
		} catch(Exception e) {
			logger.error("Upgrade module '" + this.getClass().getPackage().getName() + "' to " + getNewVersion() + " fail.", e);
			return false;
		}
	}

	/**
	 *创建表-用户token表
	 * @param conn		jdbc连接
	 * @param type		数据库类型
	 * @param tableName	sys_menu
	 * @throws SQLException
	 */
	private void createTableUserToken(Connection conn, DBType type, String tableName, String comment) throws SQLException {
		if(checkTableExist(conn,tableName))
			return;
		UpgradeTable table = new UpgradeTable("sys_user_token", comment);

		table.addColumns(new UpgradeColumn[] {
				new UpgradeColumn("id", "主键", ValueType.LONG, false, null),
				new UpgradeColumn("user_id", "用户主键", ValueType.LONG, true, null),
				new UpgradeColumn("client_secret", "客户密钥", ValueType.STRING_VARCHAR, true,32),
				new UpgradeColumn("refresh_token", "token", ValueType.STRING_VARCHAR, true, 64),
				new UpgradeColumn("expired_time", "过期时间", ValueType.DATETIME, true, null),
				new UpgradeColumn("create_time", "创建时间", ValueType.DATETIME, true, null),
				new UpgradeColumn("del_flag", "删除标识", ValueType.INT, true, null)
		});
		table.addPrimaryKeys("id");
		table.addIdentityKeys("id");
		table.doCreateTable(conn, type);
	}

	/**
	 * 检验表是否存在
	 * @param conn
	 * @param tableName
	 * @return
	 */
	public static boolean checkTableExist(Connection conn, String tableName) {
		String sqlCheck = "select 1 from " + tableName + " where 1!=1";
		boolean flag = UpgradeHelper.checkExist(conn, sqlCheck);
		if(flag)
			logger.debug("table[" + tableName + "] has exist in database.");
		return flag;
	}


}
